package com.letv.android.client.fragment;

import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Rect;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Build.VERSION;
import android.os.Bundle;
import android.os.Looper;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;

import com.letv.ads.AdsManager;
import com.letv.ads.AdsManager.VideoCallBack;
import com.letv.android.client.LetvSDK;
import com.letv.android.young.client.R;
import com.letv.android.client.listener.PlayActivityCallback;
import com.letv.android.client.widget.PlayBlock;
import com.letv.component.player.Interface.OnVideoViewStateChangeListener;
import com.letv.component.player.LetvMediaPlayerControl;
import com.letv.component.player.LetvVideoViewBuilder;
import com.letv.component.player.LetvVideoViewBuilder.Type;
//import com.letv.component.player.fourd.LetvMediaPlayerControl4D;
//import com.letv.component.player.fourd.LetvVideoViewBuilder4D;
import com.letv.component.player.utils.NativeInfos;
import com.letv.core.constant.PlayConstant;
import com.letv.core.utils.LogInfo;
import com.letv.core.utils.PlayUtils;
import com.letv.core.utils.ScreenInfoUtils;
import com.letv.core.utils.StatisticsUtils;
import com.letv.core.utils.UIsUtils;
import com.letv.datastatistics.DataStatistics;
import com.letv.datastatistics.util.LetvErrorCode;
import com.letv.datastatistics.util.PageIdConstant;
import com.letv.pp.func.CdeStateHelper;
import com.letv.pp.listener.CdeStateListener;
import com.media.ffmpeg.FFMpegPlayer;


/**
 * 播放Fragment
 */
public abstract class BasePlayFragment extends LetvBaseFragment implements MediaPlayer.OnErrorListener,
        MediaPlayer.OnPreparedListener, MediaPlayer.OnCompletionListener, FFMpegPlayer.OnCacheListener, VideoCallBack,
        PlayBlock.PlayBlockCallback {
    private ViewGroup mRoot;
    private RelativeLayout mLayout;
    protected LetvMediaPlayerControl mVideoView;

    protected PlayActivityCallback mPlayFragmentListener;
    // videoview状态变化的监听
    private OnVideoViewStateChangeListener mStateChangeListener;

    // 根据启动模式来判断加载的videoView
    private int mLaunchMode = PlayConstant.LAUNCH_MODE_URI;
    // 当前编码
    private Type mOldType;
    // 判断是否能支持硬解:0:默认走软解不显示硬解切换；1:默认走硬解播放器；
    private int mDecorderType = 0;
    private String mPageId;
    // 震撼文件地址
    private String mHaptUrl;
    /**
     * 直播还是点播
     * 点播：PLAY_TYPE_ALBUM
     * 直播：PLAY_TYPE_LIVE
     */
    private int mPlayType;
    // 是否是新启动播放
    private boolean mFirstStart = false;
    // 当前播放时间
    private int mCurrentPostion;
    // 是否锁屏
    private boolean mScreenLock = false;
    // 是否强制等待
    private boolean mEnforcementWait = false;
    // 卡顿
    private PlayBlock mPlayBlock;

    // 统计
    private Uri mPlayUri;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mRoot = (ViewGroup) inflater.inflate(R.layout.letv_fragment_play_playerlibs, null);
        mLayout = (RelativeLayout) mRoot.findViewById(R.id.play_video_layout);

        initData();

        return mRoot;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        configurationChanged();
        AdsManager.getInstance().setVideoCallBack(this);
    }

    @Override
    public void onResume() {
        super.onResume();
        if (ScreenInfoUtils.reflectScreenState(mContext) && !mFirstStart) {
            resume();
        }
        mFirstStart = false;
    }

    private void initData() {
        mPlayBlock = new PlayBlock(getActivity(), this);
    }

    /**
     * 从activity设置intent
     * 
     * @param intent
     */
    public void setIntent(Intent intent) {
        if (intent == null)
            return;

        mPageId = intent.getStringExtra(PlayConstant.PAGE_ID);
        mLaunchMode = intent.getIntExtra(PlayConstant.LAUNCH_MODE, 0);
        mHaptUrl = intent.getStringExtra(PlayConstant.HAPT_URL);
        mPlayType = intent.getIntExtra(PlayConstant.PLAY_TYPE, PlayConstant.PLAY_TYPE_ALBUM);
    }

    /**
     * 传入回调
     * 
     * @param playFragmentListener
     */
    public void setPlayFragmentListener(PlayActivityCallback playFragmentListener) {
        this.mPlayFragmentListener = playFragmentListener;
    }

    /**
     * 判断是否是新启动
     * 
     * @param firstStart
     */
    public void setFirstStart(boolean firstStart) {
        this.mFirstStart = firstStart;
    }

    /**
     * 当前是否锁屏
     * 
     * @param screenLock
     */
    public void setScreenLock(boolean screenLock) {
        this.mScreenLock = screenLock;
    }

    /**
     * 播放器状态变换的监听
     * 
     * @param stateChangeListener
     */
    public void setStateChangeListener(OnVideoViewStateChangeListener stateChangeListener) {
        this.mStateChangeListener = stateChangeListener;
        if (mVideoView != null) {
            mVideoView.setVideoViewStateChangeListener(this.mStateChangeListener);
        }
    }

    /**
     * 在setLaunchMode方法之后进行调用，根据luanchMode的值
     * 来判断加载的videoView的类型
     */
    public void initVideoview(boolean isLocal) {
        String videoFormat = LetvSDK.getInstance().getVideoFormat();
        boolean defaultStreamDecorder = LetvSDK.getInstance().getDefaultHardStreamDecorder();

        if (mVideoView != null && mLayout != null) {
            mLayout.removeView(mVideoView.getView());
        }
        if (isLocal) {
            mVideoView = LetvVideoViewBuilder.getInstants()
                                             .build(mContext.getApplicationContext(), Type.MOBILE_H264_MP4);
            mOldType = Type.MOBILE_H264_MP4;
            mDecorderType = 0;
        } else {
            LogInfo.log("clf", "...mPlayType=" + mPlayType);
            if (mPlayType == PlayConstant.PLAY_TYPE_LIVE) { // 直播
                mVideoView = LetvVideoViewBuilder.getInstants()
                                                 .build(getActivity().getApplicationContext(), Type.MOBILE_H264_M3U8);
                mOldType = Type.MOBILE_H264_M3U8;
                mDecorderType = 0;
            } else if (TextUtils.equals(mPageId, PageIdConstant.localPage)) {
                mVideoView = LetvVideoViewBuilder.getInstants()
                                                 .build(getActivity().getApplicationContext(), Type.MOBILE_H264_MP4);
                mOldType = Type.MOBILE_H264_MP4;
                mDecorderType = 0;
            } else if (TextUtils.equals(videoFormat, "no") && mLaunchMode != PlayConstant.LAUNCH_MODE_URI
                    && mLaunchMode != PlayConstant.LAUNCH_MODE_DOWNLOAD) {
                // 非mp4且非缓存和扫描的视频，用m3u8
                if (defaultStreamDecorder) {
                    mVideoView = LetvVideoViewBuilder.getInstants()
                                                     .build(mContext.getApplicationContext(), Type.MOBILE_H264_M3U8_HW);
                    mOldType = Type.MOBILE_H264_M3U8_HW;
                    mDecorderType = 1;
                } else {
                    mVideoView = LetvVideoViewBuilder.getInstants()
                                                     .build(mContext.getApplicationContext(), Type.MOBILE_H264_M3U8);
                    mOldType = Type.MOBILE_H264_M3U8;
                    mDecorderType = 0;
                }
            } else {
                if (!TextUtils.isEmpty(mHaptUrl)) {
//                    LetvMediaPlayerControl4D control4D = LetvVideoViewBuilder4D.getInstants().build(mContext,
//                            LetvVideoViewBuilder4D.Type.MOBILE_H264_MP4_4D);
//                    control4D.setHaptUrl(mHaptUrl);
//                    LogInfo.log("wlx", "= " + mHaptUrl);
//                    mHaptUrl = "";
//                    mOldType = Type.MOBILE_H264_MP4;
//                    mVideoView = control4D;
//                    mDecorderType = 0;

                    // open clf
                    // if (!NetworkUtils.isWifi() && (NetworkUtils.getNetType() != NetworkUtils.NETTYPE_NO)) {
                    // ToastUtils.show4dToast(getActivity(), getString(R.string.no_wifi));
                    // }

                } else {
                    // 播mp4
                    mVideoView = LetvVideoViewBuilder.getInstants()
                                                     .build(getActivity().getApplicationContext(), Type.MOBILE_H264_MP4);
                    mOldType = Type.MOBILE_H264_MP4;
                    mDecorderType = 0;
                }
            }
        }
        StatisticsUtils.setType(mOldType);
        addVideoView();
    }

    /**
     * 添加videoView
     */
    private void addVideoView() {
        mLayout.removeAllViews();
        if (mVideoView != null) {
            mLayout.addView(mVideoView.getView(),
                    new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
        }
        // 设置卡顿监听
        mVideoView.setOnCacheListener(this);
        mVideoView.setVideoViewStateChangeListener(mStateChangeListener);
    }

    /**
     * 切换解码方式
     * 
     * @param type
     */
    public void changeVideoView(Type type) {
        if (mOldType == type)
            return;

        if (mVideoView == null)
            return;

        mVideoView.stopPlayback();
        mVideoView = LetvVideoViewBuilder.getInstants()
                                         .build(getActivity().getApplicationContext(), type);
        addVideoView();
        // setStateChangeListener((OnVideoViewStateChangeListener) activity.getmPlayControllerPlayerLibs());
        LogInfo.log("zhuqiao", "---PlayNet---changeVideoView" + mVideoView.getClass().getSimpleName());
        mOldType = type;
        StatisticsUtils.setType(mOldType);
    }

    /**
     * 初始化播放器类型 本地播放器还是系统播放器
     * */
    public void initNativeInfos() {
        String vf = LetvSDK.getInstance().getVideoFormat();

        if (TextUtils.equals("ios", vf)) {
            NativeInfos.mOffLinePlay = false;
            NativeInfos.mIsLive = false;
        } else if (TextUtils.equals("no", vf)) {
            NativeInfos.mOffLinePlay = true;
            NativeInfos.mIfNative3gpOrMp4 = true;
            NativeInfos.mIsLive = false;
        }
    }

    /**
     * 播放在线
     * */
    public void playNet(String uriString, boolean isDolby, int msec) {
        LogInfo.log("clf", "开始播放playNet 播放地址uriString=" + uriString);
        if (TextUtils.isEmpty(uriString) || getActivity() == null) {
            return;
        }
        if (!StatisticsUtils.isFirstPlay()) {
            StatisticsUtils.setFirstPlay(true);
            // 统计-login
            StatisticsUtils.statisticsLogin(mContext, 4);
            // 统计-env
            StatisticsUtils.statisticsEnv(mContext);
        }
        // 如果VideoView为空则初始化VideoView
        LogInfo.log("clf", "开始播放playNet mVideoView=" + mVideoView);
        if (mVideoView == null) {
            initVideoview(false);
        }

        if (mPlayType == PlayConstant.PLAY_TYPE_LIVE) { // 直播
            mVideoView.setVideoPath(uriString);
        } else { // 点播切换解码方式处理
            if (TextUtils.equals("ios", LetvSDK.getInstance().getVideoFormat())) {
                if (LetvSDK.getInstance().getDefaultHardStreamDecorder()) {
                    changeVideoView(Type.MOBILE_H264_M3U8_HW);
                } else {
                    changeVideoView(Type.MOBILE_H264_M3U8);
                }
            } else {
                changeVideoView(Type.MOBILE_H264_MP4);
            }

            // 播放是否是高清 1：极速，2：流畅，3：高清， 4：超清
            int playLevel = 0;
            if (mPlayFragmentListener != null) {
                playLevel = mPlayFragmentListener.getPlayLevel();
            }
            LogInfo.log("zhuqiao", "oldType:" + mOldType + "====level:" + playLevel);
            mVideoView.setVideoPlayUrl(PlayUtils.getPlayUrl(uriString, mOldType, playLevel));
        }

        mPlayUri = Uri.parse(uriString);
        NativeInfos.mOffLinePlay = false;
        initNativeInfos();
        NativeInfos.mIsLive = mPlayType == PlayConstant.PLAY_TYPE_LIVE;
        if (isDolby) {
            NativeInfos.mOffLinePlay = true;
            NativeInfos.mIfNative3gpOrMp4 = true;
            NativeInfos.mIsLive = false;
        }

        mCdeStateHelper.start(uriString);
        mVideoView.setOnErrorListener(this);
        mVideoView.setOnCompletionListener(this);
        mVideoView.setOnPreparedListener(this);
        mVideoView.getView().requestFocus();
        mVideoView.setEnforcementPause(false);
        mVideoView.setEnforcementWait(false);
        if (msec > 0) {
            mVideoView.seekTo(msec);
        }
        if (!mScreenLock) { // 锁屏不播放
            mVideoView.getView().setVisibility(View.VISIBLE);
            mVideoView.start();
        }
    }

    /**
     * onResume时处理播放
     */
    public void resume() {
        if (mVideoView != null) {
            if (mPlayType == PlayConstant.PLAY_ALBUM) { // 点播做seek处理
                if (mVideoView.getLastSeekWhenDestoryed() != 0) {
                    mVideoView.seekTo(mVideoView.getLastSeekWhenDestoryed());
                } else {
                    if (mCurrentPostion != 0) {
                        if (mVideoView != null) {
                            mVideoView.seekTo(mCurrentPostion);
                        }
                    }
                }
            }

            mVideoView.start();
            if (mPlayFragmentListener != null) {
                mPlayFragmentListener.callAdsInterface(PlayConstant.ON_VIDEO_RESUME, false);
                mPlayFragmentListener.cancelLongTimeWatch();
            }
        }
    }

    /**
     * 暂停
     */
    public void pause() {
        if (mVideoView != null) {
            mVideoView.pause();
        }
        if (mPlayFragmentListener != null) {
            mPlayFragmentListener.callAdsInterface(PlayConstant.ON_VIDEO_PAUSE, true);
        }
    }

    /**
     * 停止
     */
    public void stopPlayback() {
        if (mVideoView != null) {
            mVideoView.stopPlayback();
        }
    }

    /**
     * 销毁mVideoView，释放MediaPlay资源
     */
    public void destroyVedioView() {
        if (mVideoView != null && mLayout != null) {
            mVideoView.stopPlayback();
            mLayout.removeView(mVideoView.getView());
        }
        mOldType = null;
        mVideoView = null;
        StatisticsUtils.setType(null);
    }

    /**
     * 跳到
     */
    public void seekTo(int msec) {
        /**
         * 针对小米三 进行特需处理（小米3 & 断网 & 在线视频）
         */
        if (mVideoView != null) {
            mVideoView.seekTo(msec);
        }
    }

    /**
     * 快进
     */
    public void forward() {
        if (mVideoView != null) {
            mVideoView.forward();
        }
    }

    /**
     * 快退
     */
    public void rewind() {
        if (mVideoView != null) {
            mVideoView.rewind();
        }
    }

    /**
     * 是否在播放中
     */
    public boolean isPlaying() {
        return mVideoView == null ? false : mVideoView.isPlaying();
    }

    /**
     * 是否暂停
     */
    public boolean isPaused() {
        return mVideoView == null ? false : mVideoView.isPaused();
    }

    /**
     * 得到当前时间点
     */
    public int getCurrentPosition() {
        return mVideoView.getCurrentPosition();
    }

    /**
     * 得到当前缓冲时间点
     */
    public int getBufferPercentage() {
        return mVideoView.getBufferPercentage();
    }

    /**
     * 得到总时长
     */
    public int getDuration() {
        return mVideoView.getDuration();
    }

    /**
     * 是否进入播放状态（包括准备完成，播放，暂停，完成等）
     */
    public boolean isInPlaybackState() {
        return mVideoView.isInPlaybackState();
    }

    public void setEnforcementWait(boolean enforcementWait) {
        this.mEnforcementWait = enforcementWait;
        if (mVideoView != null) {
            mVideoView.setEnforcementWait(enforcementWait);
        }
    }

    public boolean isEnforcementWait() {
        return mEnforcementWait;
    }

    public void setEnforcementPause(boolean enforcementPause) {
        if (mVideoView != null) {
            mVideoView.setEnforcementPause(enforcementPause);
        }
    }

    public boolean isEnforcementPause() {
        if (mVideoView != null) {
            return mVideoView.isEnforcementPause();
        }

        return false;
    }

    /**
     * 缩放播放view
     */
    private void configurationChanged() {
        if (UIsUtils.isLandscape(getActivity())) {
            UIsUtils.zoomViewFull(mContext,mRoot);
        } else {
            UIsUtils.zoomView(mContext,320, 180, mRoot);
        }
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        configurationChanged();
    }

    @Override
    public void onPause() {
        super.onPause();
        pause();
        if (mVideoView != null) {
            mCurrentPostion = mVideoView.getCurrentPosition();
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        mPlayUri = null;
        destroyVedioView();
    }

    @Override
    public void onCompletion(MediaPlayer mp) {
        if (mPlayFragmentListener != null) {
            mPlayFragmentListener.callAdsInterface(PlayConstant.ON_VIDEO_COMPLATE, false);
        }
    }

    @Override
    public void onPrepared(MediaPlayer mp) {
    }

    @Override
    public boolean onError(MediaPlayer mp, int what, int extra) {
        // 统计
        StringBuilder sb = new StringBuilder();
        if (mPlayUri != null) {
            sb.append("playurl=").append(mPlayUri.toString());
        }

        if (what == -91) {
            // 播放视频超时 ，上传错误码
            DataStatistics.getInstance().sendErrorInfo(getActivity(), "0", "0", LetvErrorCode.VIDEO_PLAY_TIMEOUT, null,
                    sb.toString(), null, null, null, null);
        } else if (what == -103) {
            // 播放的视频文件不合法 ，上传错误码
            DataStatistics.getInstance().sendErrorInfo(getActivity(), "0", "0",
                    LetvErrorCode.VIDEO_PLAY_NOT_LEGITIMATE, null, sb.toString(), null, null, null, null);
        } else {
            // 播放视频文件其它错误 ，上传错误码
            DataStatistics.getInstance().sendErrorInfo(getActivity(), "0", "0", LetvErrorCode.VIDEO_PLAY_OTHER_ERROR,
                    null, sb.toString(), null, null, null, null);
        }
        if (mPlayFragmentListener != null) {
            mPlayFragmentListener.callAdsInterface(PlayConstant.ON_VIDEO_ERROR, false);
        }
        return false;
    }

    // -----------------广告回调--------------------
    @Override
    public void resumeVideo() {
        if (mVideoView != null) {
            mVideoView.start();
        }
    }

    @Override
    public void pauseVideo() {
        if (mVideoView != null) {
            mVideoView.pause();
        }
    }

    @Override
    public Rect getPlayerRect() {
        Rect rect = new Rect();
        mRoot.getGlobalVisibleRect(rect);
        return rect;
    }

    @Override
    public void onCache(FFMpegPlayer arg0, int blockInfo, int arg2, long arg3) {
        if (mPlayFragmentListener == null) {
            return;
        }
        if (mPlayFragmentListener == null) {
            return;
        }
        if (blockInfo == FFMpegPlayer.MEDIA_CACHE_START) {
            mPlayFragmentListener.blockStart();
            mPlayBlock.blockStart();
        } else if (blockInfo == FFMpegPlayer.MEDIA_CACHE_END) {
            mPlayFragmentListener.blockEnd();
            mPlayBlock.blockEnd();
        }
    }

    @Override
    public void blockTwiceAlert() {
        if (mPlayFragmentListener != null) {
            mPlayFragmentListener.blockTwiceAlert();
        }
    }

    // -----------------广告回调--------------------

    private final CdeStateHelper mCdeStateHelper = new CdeStateHelper(new CdeStateListener() {

        @Override
        public void onDownloadDurationChange(int downloadDuration) {
            // 返回值downloadDuration为当前影片已下载数据的时长，其值可能比从播放器拿到的duration值大，该情况是正常的。
            // 若该值大于duration，则表示缓冲100%
        }
    }, Looper.myLooper());

    // -------------------统计-----------------

}
